const qiNiuYun = require("qiniu");
const qiniu = require("qiniu-js");
const {AccessKey, SecretKey, bucket, overWriteFileName} = require("./config");

//鉴权对象mac
const mac = new qiNiuYun.auth.digest.Mac(AccessKey, SecretKey);
//覆盖上传上传凭证

/*
@name: getFileByPreFix
@param {None}
@returns {Promise}
@description: 根据前缀返回oss中的文件列表
@author: ChangHao
@time: 2021-01-14 11:56:58
*/
const getFileByPreFix = function () {
    const listOptions = {
        prefix: 'xml',
    }
    const config = new qiNiuYun.conf.Config();
    const bucketManager = new qiNiuYun.rs.BucketManager(mac, config);
    return new Promise((resolve, reject) => {

        bucketManager.listPrefix(bucket, listOptions, function (err, respBody, respInfo) {
            if (err) {
                reject(err)
            } else {
                if (respBody.items.length > 0) {
                    const deleteOptionArr = respBody.items.reduce((acc, current) => {
                        return [...acc, qiNiuYun.rs.deleteOp(bucket, current.key)]
                    }, [])
                    console.log('执行删除=======xmlSearch===========⚠️')
                    bucketManager.batch(deleteOptionArr, (err, respBody, respInfo) => {
                        if (parseInt(respInfo.statusCode / 100) == 2) {
                            resolve(respBody)
                        }
                    })
                } else {
                    console.log('无项目可以删除')
                    resolve(true)
                }
            }
        })

    })
}
getFileByPreFix().then(res => {
    const cdnManger = new qiNiuYun.cdn.CdnManager(mac)
    cdnManger.refreshUrls([
        "http://qiniuyun.quancundexiwang.wang/xmlSearch.xml"
    ],err=>{
        if(!err){
            console.log('刷新url成功')
        }
    })
    const options = {
        scope: bucket,
        expires: 7200,
    };
    const putPolicy = new qiNiuYun.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    console.log(uploadToken);
    const uploadConfig = {
        useCdnDomain: false, // 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
        retryCount: 5, // 上传自动重试次数（整体重试次数，而不是某个分片的重试次数）；默认 3 次（即上传失败后最多重试两次）。
        region: qiniu.region.z2, //区域
    };

    const putExtra = new qiNiuYun.form_up.PutExtra({
        fname: overWriteFileName,
    });
    const key = overWriteFileName;
    var formUploader = new qiNiuYun.form_up.FormUploader(uploadConfig);
    const localFile = "./public/xmlSearch.xml";
    formUploader.putFile(
        uploadToken,
        key,
        localFile,
        putExtra,
        function (respErr, respBody, respInfo) {
            if (respErr) {
                throw respErr;
            }
            if (respInfo.statusCode == 200) {
                console.log(respBody);
                console.log(`${respBody.key}文件已经配置到七牛云`);
            } else {
                console.log(respInfo.statusCode);
                console.log(respBody);
            }
        }
    );

})
getFileByPreFix()
